import os
import os.path

def which(executable):
    for path in os.environ['PATH'].split(':'):
        exec_path = os.path.join(path, executable)
        if os.path.exists(exec_path):
            return exec_path
    else:
        return executable

def custom_build(executable, args, src_suffix, suffix=None,
            intermediate_exts=None):
    builder_args = {'action' : ' '.join([which(executable), args]),
                    'src_suffix' : src_suffix}
    if suffix:
        builder_args['suffix'] = suffix
    build = Builder(**builder_args)
    env = Environment(BUILDERS={'_build_code':build})
    if intermediate_exts:
        def build_and_clean(name):
            compile_ = env._build_code(name)
            for ext in intermediate_exts:
                Clean(compile_, '.'.join([name, ext]))
        return build_and_clean
    else:
        return lambda x: env._build_code(x)

Export('custom_build')


build_files = []
for entry in os.listdir(os.getcwd()):
    if entry.startswith('.') or not os.path.isdir(entry):
        continue
    path = os.path.join(entry, 'SConstruct')
    if os.path.exists(path):
        build_files.append(path)

SConscript(build_files)
